package com.yoga.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yoga.model.Classroom;
import com.yoga.service.ClassroomService;
import com.yoga.service.UploadService;
import com.yoga.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author yan
 * @date 2025/8/16
 */
@RestController
@RequestMapping(value = "/api/v1/classroom", produces = MediaType.APPLICATION_JSON_VALUE)
public class ClassroomApi {

    private ClassroomService classroomService;
    private UploadService uploadService;

    @Autowired
    public void setClassroomService(ClassroomService classroomService) {
        this.classroomService = classroomService;
    }
    @Autowired
    public void setUploadService(UploadService uploadService) {
        this.uploadService = uploadService;
    }

    @GetMapping
    public ResponseEntity<JsonResult<?>> getAllClassroom(@RequestParam(defaultValue = "1") Integer pageNo,
                                                         @RequestParam(defaultValue = "10") Integer pageSize, Classroom classroom) {
        Page<Classroom> page = new Page<>(pageNo, pageSize);
        page = this.classroomService.searchAll(page, classroom);
        return ResponseEntity.ok(JsonResult.success(page));
    }

    @GetMapping("/all")
    public ResponseEntity<JsonResult<?>> findAll() {
        List<Classroom> classrooms = this.classroomService.findAll();
        return ResponseEntity.ok(JsonResult.success(classrooms));
    }
    @DeleteMapping
    public ResponseEntity<JsonResult<?>> deleteByIds(@RequestBody Integer[] ids) {
        int count = this.classroomService.deleteById(List.of(ids));
        return ResponseEntity.ok(JsonResult.success(count));
    }

    @PostMapping
    public ResponseEntity<JsonResult<?>> add(@RequestBody Classroom classroom) {
        boolean flag = this.classroomService.add(classroom);
        if (flag) {
            return ResponseEntity.ok(JsonResult.success(classroom));
        } else {
            return ResponseEntity.ok(JsonResult.fail("添加失败"));
        }
    }

    @PutMapping
    public ResponseEntity<JsonResult<?>> update(@RequestBody Classroom classroom) {
        boolean flag = this.classroomService.update(classroom);
        if (flag) {
            return ResponseEntity.ok(JsonResult.success(classroom));
        } else {
            return ResponseEntity.ok(JsonResult.fail("修改失败"));
        }
    }

    @PostMapping("/avatar")
    public ResponseEntity<JsonResult<?>> uploadAvatar(MultipartFile file) {
        String path = this.uploadService.uploadImage(file, "classroom_portrait");
        return ResponseEntity.ok(JsonResult.success(path));
    }
}

